//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    list: [{
      id: 1,
      name: "铅笔",
      price: 1,
      count: 1,
      total: 1
    }, {
      id: 2,
      name: "橡皮",
      price: 1.5,
      count: 1,
      total: 1
    }, {
      id: 3,
      name: "尺子",
      price: 0.5,
      count: 1,
      total: 0.5
    }, {
      id: 4,
      name: "涂改液",
      price: 2.5,
      count: 1,
      total: 2.5
    }, {
      id: 5,
      name: "中性笔",
      price: 2,
      count: 1,
      total: 2
    }],
    total: 0,
    sortType: 0,
    sortTypeText: ""
  },

  onLoad: function (e) {

  },
  tapPlus: function (e) {
    //处理对应的商品count增加一个，并计算该商品的总价total
    let id = e.currentTarget.dataset.id;
    let list = this.data.list;
    list.forEach(element => {
      if (element.id == id) {
        element.count++;
        element.total = element.count * element.price;
      }
    });
    this.setData({
      list: list
    })
  },
  tapMinus: function (e) {
    //处理对应的商品count减少一个，并计算该商品的总价total
    let id = e.currentTarget.dataset.id;
    let list = this.data.list;
    list.forEach(element => {
      if (element.id == id) {
        element.count = element.count - 1 < 0 ? 0 : element.count - 1;
        element.total = element.count * element.price;
      }
    });
    this.setData({
      list: list
    })
  },
  sort: function () {
    //根据商品的total进行排序，每点击一次，更换一下排序规则。如第一次点大到小，第二次点从小到大等.
    let sortType = this.data.sortType;
    sortType = sortType + 1 > 2 ? 0 : sortType + 1;
    let list = this.data.list;
    list.sort((a,b) => {
      if (sortType == 1) {
        return a.total - b.total;
      } else if (sortType == 2) {
        return b.total - a.total;
      } else {
        return a.id - b.id;
      }
    });
    this.setData({
      sortType: sortType,
      list: list
    });
    this.getSortType();
  },
  sum: function () {
    //将所有商品的total列合计，结果赋值到data的total中
    let list = this.data.list;
    let total = 0;
    list.forEach(element => {
      total += element.total;
    });
    this.setData({
      total: total
    })
  },
  getSortType() {
    let sortType = this.data.sortType;
    let temp = "";
    switch (sortType) {
      case 1:
        temp = " (合计↑)";
        break;
      case 2:
        temp = " (合计↓)";
        break;
      default:
        break;
    }
    this.setData({
      sortTypeText: temp
    })
  }
})